package com.yk.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yk.api.system.dto.DeviceDTO;
import com.yk.api.system.dto.GroupDTO;
import com.yk.common.core.utils.LoginHelper;
import com.yk.system.entity.GroupDevice;
import com.yk.system.mapper.GroupDeviceMapper;
import com.yk.system.service.GroupDeviceService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 *
 * @author lmx
 * @date 2023/11/24 17:22
 */
@Service
public class GroupDeviceServiceImpl extends ServiceImpl<GroupDeviceMapper, GroupDevice> implements GroupDeviceService{

    @Override
    public int batchInsert(List<GroupDevice> list) {
        return baseMapper.batchInsert(list);
    }

    @Override
    public List<DeviceDTO> listByGroupId(Long groupId, Long userId) {
        return baseMapper.listByGroupId(groupId, userId);
    }

    @Override
    public List<DeviceDTO> listByGroupIdByParam(DeviceDTO param) {
        param.setCreatedBy(LoginHelper.getLoginUserId());
        return baseMapper.listByGroupIdByParam(param);
    }

    @Override
    public List<GroupDTO> listByDeviceId(Long deviceId) {
        Long userId = LoginHelper.getLoginUserId();
        return baseMapper.listByDeviceId(deviceId, userId);
    }

    @Override
    public List<GroupDTO> listByDeviceIdAndUserId(Long deviceId, Long userId) {
        return baseMapper.listByDeviceId(deviceId, userId);
    }

    public GroupDevice getLastByOrderDesc(Long id, Long userId){
        return baseMapper.getLastByOrderDesc(id, userId);
    }

    @Override
    public void relevancyDevice(Long id, Long userId, List<Long> groupIds) {
        // 删除关联
        LambdaQueryWrapper<GroupDevice> lambda = new LambdaQueryWrapper<>();
        lambda.eq(GroupDevice::getDeviceId, id);
        lambda.eq(GroupDevice::getCreatedBy, userId);
        List<GroupDevice> groupDevices = baseMapper.selectList(lambda);
        baseMapper.delete(lambda);
        // 需要关联
        if (CollUtil.isNotEmpty(groupIds)) {
            List<GroupDevice> addList = CollUtil.newArrayList();
            groupIds.forEach(it -> {
                List<GroupDevice> gdList = groupDevices.stream()
                        .filter(gr -> gr.getGroupId().equals(it))
                        .collect(Collectors.toList());
                // 新增的关联关系
                if (CollUtil.isEmpty(gdList)){
                    // 如果没有找到，就取最后一个
                    GroupDevice groupDevice = getLastByOrderDesc(it, userId);
                    int sort = 1;
                    if (Objects.nonNull(groupDevice) && groupDevice.getSort()!= null){
                        sort += groupDevice.getSort();
                    }
                    addList.add(new GroupDevice(it, id, userId, sort));
                }else {
                    // 原来的关联关系
                    Optional<GroupDevice> first = gdList.stream().findFirst();
                    if (first.isPresent()){
                        GroupDevice groupDevice = first.get();
                        addList.add(new GroupDevice(it, id, userId, groupDevice.getSort()));
                    }
                }
            });
            batchInsert(addList);
        }
    }
}
